<?php
/**
 * Description of session
 *
 * @author JD Russell
 */
include_once("shared-functions.php");
@session_start();

/**
 * Validates that user name and password are valid and creates session. Session
 * is tracked by PHP session ID and relevant information is stored in Session
 * table.
 *
 * @param str $userId
 * @param str $password
 * @return bool - Returns true if session was successfully created. Else returns
 * false.
 * @author JD Russell
 * @version 1.0
 */
function CreateSession ($userId, $password)
{
    try
    {
        $link = connect_db();

        $hash = gen_passwd_hash($password);
        $query = "SELECT `userID`, `userName`, `password` FROM `User` WHERE `userName` LIKE '".$userId."' AND `password` = '".$hash."';";
        $result = mysql_query($query,$link);
        if(mysql_num_rows($result)<1)
        {
            $_SESSION['login_error']="Incorrect user name or password entered.";
            return false;
        }
        $userDetails = mysql_fetch_array($result,MYSQL_BOTH);
        $query = "INSERT INTO `Session` VALUES ('".session_id()."','".
                                                   $userDetails['userID']."','".
                                                   time()."','".
                                                   time()."','".
                                                   $_SERVER['REMOTE_ADDR']."');";
        $result=mysql_query($query,$link);
        if($result===false)
        {
            $query="UPDATE `Session` SET `lastTime`='".time()."' WHERE `sessionID`='".session_id()."';";
            $result = mysql_query($query,$link);
            if($result===false)
            {
                $_SESSION['login_error']="Could not create session.";
                return false;
            }
        }
        
        return true;

    }
    catch (Exception $exception)
    {
        $_SESSION['error']=$exception->getMessage();
        return false;
    }
}

/**
 * Function determines whether or not seession is a valid, authenticated session.
 *
 * @return bool - Returns true is session is still valid. Else, returns false.
 * @author JD Russell
 * @version 1.0
 */
function IsValidSession()
{
    try
    {
        $link = connect_db();

        $query = "SELECT * FROM `Session` WHERE `sessionID` = '".session_id()."';";
        $result = mysql_query($query,$link);
        if($result===false)
        {
            $_SESSION['error']="Could not perform query.";
            return false;
        }
        if(mysql_num_rows($result)>0)
        {
            $sessionDetails = mysql_fetch_array($result);
            if($sessionDetails['lastTime']<time()-1200)
            {
                $_SESSION['error']="Session expired.";
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    catch (Exception $exception)
    {
        $_SESSION['error']=$exception->getMessage();
        return false;
    }
}

/**
 * Updates session timestamp to current time.
 *
 * @return bool - Returns true on success, else fail.
 * @author JD Russell
 * @version 1.0
 */
function RefreshSession()
{
    try
    {
        $link = connect_db();
        
        $query = "UPDATE `Session` SET `lastTime`='".time()."' WHERE `sessionID` = '".session_id()."';";
        $result = mysql_query($query, $link);
        if($result===false)
        {
            $_SESSION['error']="Could not refresh session.";
            return false;
        }
        else if(mysql_affected_rows()==0)
        {
            $_SESSION['error']="Session is not valid.";
            return false;
        }
        else
        {
            return true;
        }
    }
    catch (Exception $exception)
    {
        $_SESSION['error']=$exception->getMessage();
        return false;
    }
}

/**
 * Retrieves userID for current session.
 *
 * @return mixed - Returns userID for session on success. Else, returns false.
 * @author JD Russell
 * @version 1.0
 */
function GetSessionUser()
{
    try
    {
        $link = connect_db();
        $query = "SELECT `userID` FROM `Session` WHERE `sessionID` = '".session_id()."';";
        $result = mysql_query($query, $link);
        if($result===false)
        {
            $_SESSION['error']="Could not get session details.";
            return false;
        }
        else
        {
            $userDetails = mysql_fetch_array($result,MYSQL_BOTH);
            return $userDetails['userID'];
        }
    }
    catch (Exception $exception)
    {
        $_SESSION['error']=$exception->getMessage();
        return false;
    }
}

/**
 * Removes current session and all sessions that have expired.
 *
 * @return bool - Returns true on success, else fail.
 * @author JD Russell
 * @version 1.0
 */
function SessionCleanup()
{
    try
    {
        $link = connect_db();
        $query = "DELETE FROM `Session` WHERE `sessionID`='".session_id()."' OR `lastTime` < ".(time()-1200).";";
        $result = mysql_query($query,$link);
        if($result===false)
        {
            $_SESSION['error']="Could not delete session.";
            return false;
        }
        else
        {
            return true;
        }

    }
    catch (Exception $exception)
    {
        $_SESSION['error']=$exception->getMessage();
        return false;
    }

}

?>
